//
//  AlipayManager.swift
//  GhostWorld
//
//  Created by Kam on 2018/7/5.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation

class AlipayManager {
  // MARK: - Singleton
  static let shared = AlipayManager()
  private init() { }
  
  enum PayOrderStatus: Int {
    
    /*
     9000  订单支付成功
     8000  正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     4000  订单支付失败
     6001  用户中途取消
     6002  网络连接出错
     6004  支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     其它  其它支付错误
     */
    case success = 9000
    case processing = 8000
    case failed = 4000
    case user_abort = 6001
    case network_failed = 6002
    case unknown = 6004
    case other = -1
    
    func getMessage() -> String {
      switch self {
      case .success:
        return "订单支付成功"
      case .processing:
        return "订单正在处理中"
      case .failed:
        return "订单支付失败"
      case .user_abort:
        return "用户取消支付"
      case .network_failed:
        return "网络连接出错"
      case .unknown:
        return "支付结果未知"
      case .other:
        return "支付宝出现了一个诡异的错误"
      }
    }
  }
  
  var refIdentifier: Int = -1
  
  func process(orderResponse: [AnyHashable: Any]?, completion: @escaping (Bool, String) -> Void) {
    var payOrderStatus = PayOrderStatus.unknown
    guard let responseDict = orderResponse as? [String: Any] else {
      completion(false, payOrderStatus.getMessage())
      return
    }
    
    if let codeString = responseDict["resultStatus"] as? String,
      let code = Int(codeString),
      let status = PayOrderStatus(rawValue: code) {
      payOrderStatus = status
    }
    
    switch payOrderStatus {
    case .success:
      if let resultString = responseDict["result"] as? String,
        let data = resultString.data(using: .utf8) {
        do {
          let resultDict = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
          
          if let payResponseDict = resultDict["alipay_trade_app_pay_response"] as? [String: Any],
            let transactionIdentifier = payResponseDict["trade_no"] as? String {
            PurchaseUploadData.save (
              platform: .alipay,
              type: .token,
              refID: refIdentifier,
              transactionJSON: resultString,
              transactionID: transactionIdentifier
            )
            PurchaseUploader.shared.upload()
            completion(true, "购买成功")
          } else {
            completion(false, "支付宝信息错误")
          }
        } catch {
          completion(false, "支付宝信息错误")
        }
      } else {
        completion(false, "支付宝信息错误")
      }
    default:
      completion(false, payOrderStatus.getMessage())
      break
    }
    refIdentifier = -1
  }
}
